/**
 * Copyright (C), 2020-2021 by colley.ma
 * File Name: DefaultRedisScript.java
 * Encoding: UTF-8
 * Date: 2021年3月26日 下午4:23:29
 * History:
 */
package com.swak.frame.script;

import java.io.IOException;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.lang.Nullable;
import org.springframework.scripting.ScriptSource;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.scripting.support.StaticScriptSource;
import org.springframework.util.Assert;

import com.swak.frame.exception.SwakScriptNotFoundException;
import com.swak.frame.util.DigestUtils;

public class DefaultRedisScript implements RedisScript, InitializingBean {

    private final Object shaModifiedMonitor = new Object();

    private @Nullable ScriptSource scriptSource;
    private @Nullable String sha1;

    /**
     * Creates a new {@link DefaultRedisScript}
     */
    public DefaultRedisScript() {}

    /**
     * Creates a new {@link DefaultRedisScript}
     *
     * @param script must not be {@literal null}.
     * @param resultType can be {@literal null}.
     */
    public DefaultRedisScript(String script) {
        this.setScriptText(script);
    }

    @Override
    public void afterPropertiesSet() {
        Assert.state(this.scriptSource != null,
            "Either script, script location," + " or script source is required");
    }

    
    @Override
    public String getSha1() {

        synchronized (shaModifiedMonitor) {
            if (sha1 == null || scriptSource.isModified()) {
                this.sha1 = DigestUtils.sha1DigestAsHex(getScriptAsString());
            }
            return sha1;
        }
    }

    @Override
    public String getScriptAsString() {

        try {
            return scriptSource.getScriptAsString();
        } catch (IOException e) {
            throw new SwakScriptNotFoundException("Error reading script text", e);
        }
    }

    /**
     * @param scriptText The script text
     */
    public void setScriptText(String scriptText) {
        this.scriptSource = new StaticScriptSource(scriptText);
    }

    /**
     * @param scriptLocation The location of the script
     */
    public void setLocation(Resource scriptLocation) {
        this.scriptSource = new ResourceScriptSource(scriptLocation);
    }

    /**
     * @param scriptSource A @{link {@link ScriptSource} pointing to the script
     */
    public void setScriptSource(ScriptSource scriptSource) {
        this.scriptSource = scriptSource;
    }
}
